import { getSessionStorage, setSessionStorage } from '@/utils'
import { StorageEnum } from '@/enums/storageEnum'
import { ChartEditStorage } from '@/store/modules/chartEditStore/chartEditStore.d'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { getProject, getDesignModelContent } from '@/api/screen'

const chartEditStore = useChartEditStore()

export interface ChartEditStorageType extends ChartEditStorage {
  id: string
}

// 根据路由 id 获取存储数据的信息
export const getSessionStorageInfo = async () => {
  const urlHash = document.location.hash
  const toPathArray = urlHash.split('/')
  const id = toPathArray && toPathArray[toPathArray.length - 1]
  const res = await getProject({ sid: id })
  console.log('aaaa2222', id, res)
  setSessionStorage('projectInfo', res.data)
  if (res.code === 200) {
    //获取内容
    const model = await getDesignModelContent({ sid: res.data.designModelSid })
    console.log('model2222', model)
    if (model.code === 200) {
      //设置内容
      setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, [{ id, ...model.data.content }])
    }
  }

  const storageList: ChartEditStorageType[] = getSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST)

  if (storageList) {
    for (let i = 0; i < storageList.length; i++) {
      if (id.toString() === storageList[i]['id']) {
        const { editCanvasConfig, requestGlobalConfig, componentList } = storageList[i]
        chartEditStore.editCanvasConfig = editCanvasConfig
        chartEditStore.requestGlobalConfig = requestGlobalConfig
        chartEditStore.componentList = componentList
        return storageList[i]
      }
    }
  }
}
